﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 该脚本挂载到集群的各个对象上
/// </summary>
public class CrowAI : MonoBehaviour
{
    private Animation mCrowAnim { get; set; }
    //各地所受的力
    private Vector3 mSumForce = Vector3.zero;
    //个体重量
    private float mWeight = 2.0f;
    //个体速度
    private Vector3 mVelocity = Vector3.forward;
    //目标
    private Transform mTarget;         

    private void Start()
    {
        mTarget = GameObject.Find("Target").transform;

        Invoke("InitCrowAnim", Random.Range(0, 2));          

        //循环调用检测附近的个体
        InvokeRepeating("GetForce", 0.0f, 20f);
    }

    private void InitCrowAnim()
    {       
        mCrowAnim = this.GetComponentInChildren<Animation>();
        if (mCrowAnim)
        {
            mCrowAnim.CrossFade("CrowFlap");
        }
    }

    private void GetForce()
    {        
        IStrategy strategy = null;
        //获得分离的力
        strategy = new SeparationStrategy(this.transform, 2f);
        Vector3 separationForce = strategy.GetForce();        

        //获得队列的力
        strategy = new QueueStrategy(this.transform, 6.0f);
        Vector3 queueForce = strategy.GetForce();

        //获得聚集的力
        strategy = new GatherStrategy(this.transform, 6.0f);
        Vector3 gatherForce = strategy.GetForce();

        mSumForce = Vector3.zero;
        mSumForce += separationForce;
        mSumForce += queueForce;
        //mSumForce += gatherForce;

        //恒力
        Vector3 targetDir = mTarget.position - transform.position;
        mSumForce += (targetDir.normalized - transform.forward) * 4;
    }

    private void Update()
    {
        //牛顿第二定律获取加速度
        Vector3 acceleration = mSumForce / mWeight;
        //速度
        mVelocity += acceleration * Time.deltaTime;
        //朝向
        transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(mVelocity), Time.deltaTime * 3);
        //位移
        transform.Translate(transform.forward * Time.deltaTime * mVelocity.magnitude, Space.World);        
    }
}
